package com.lilicould.controller;

import com.lilicould.entity.Account;
import com.lilicould.entity.Tenant;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.lilicould.service.impl.AccountServiceImpl;

import java.io.IOException;

@WebServlet("/register/tenant")
public class RegisterTenantController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        // 获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        String bankAccount = req.getParameter("bankAccount");
        String emergencyName = req.getParameter("emergencyName");
        String emergencyPhone = req.getParameter("emergencyPhone");
        String phone = req.getParameter("phone");

        Account account = new Account(null, username, password, "tenant", null, (byte) 1);
        Tenant tenant = new Tenant(null, name, bankAccount, emergencyName, emergencyPhone);
        AccountServiceImpl accountService = new AccountServiceImpl();

        // 检查用户名是否存在
        if (accountService.checkUsername(username)) {
            req.setAttribute("error", "用户名已存在");
            req.getRequestDispatcher("../register.jsp").forward(req, resp);
            return;
        }

        boolean result = accountService.registerTenant(account, tenant, phone);
        if (result) {
            req.getRequestDispatcher("/login").forward(req, resp);
        }
    }
}
